/*
 *  Copyright (C) 2011 JiangHongTiao <jjurco.sk_gmail.com>
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sk.lieskove.jianghongtiao.websearch.api.google.search;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author xjuraj
 */
class GWSCursorImpl implements GWSCursor {

    private JSONObject gWSCursor;
    private String moreResultsUrl;
    private int currentPageIndex;
    private String estimatedResultCount;
    private List<GWSPage> gWSPages = new ArrayList<GWSPage>();

    public GWSCursorImpl(JSONObject gWSCursor) throws JSONException {
        if (gWSCursor == null) {
            throw new NullPointerException("JSON object is null.");
        }
        this.gWSCursor = gWSCursor;
        parseGWSCursor(gWSCursor);
    }

    public Collection<GWSPage> getPages() {
        return Collections.unmodifiableList(gWSPages);
    }

    public String getEstimatedResultCount() {
        return estimatedResultCount;
    }

    public Integer getCurrentPageIndex() {
        return currentPageIndex;
    }

    public String getMoreResultsUrl() {
        return moreResultsUrl;
    }

    private void parseGWSCursor(JSONObject gWSCursor) throws JSONException {

        moreResultsUrl = gWSCursor.getString("moreResultsUrl");

        if (!gWSCursor.isNull("currentPageIndex")) {
            currentPageIndex = gWSCursor.getInt("currentPageIndex");
        } else {
            currentPageIndex = 0;
        }
        if (!gWSCursor.isNull("estimatedResultCount")) {
            estimatedResultCount = gWSCursor.getString("estimatedResultCount");
        } else {
            estimatedResultCount = "0";
        }
        if (!gWSCursor.isNull("pages")) {
            JSONArray pg = gWSCursor.getJSONArray("pages");
            for (int i = 0; i < pg.length(); i++) {
                JSONObject page = pg.getJSONObject(i);
                gWSPages.add(new GWSPageImpl(page));
            }
        }


    }
}
